package uk.co.accolade.clash.multicast;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.io.IOException;
import java.util.Arrays;

public class MulticastTest {

    public static void main(String[] args) throws IOException {
        InetAddress group = InetAddress.getByName("228.5.6.7");
        MulticastSocket s = new MulticastSocket(6789);
        s.joinGroup(group);
        FinishedSending finished = new FinishedSending();
        new Thread(new ReceiveOneMessage(s, group, finished)).start();

        String msg = "Hello";
        while( !finished.done ) {
            DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
                    group, 6789);
            s.send(hi);
        }

        s.leaveGroup(group);
    }
}

class FinishedSending {
    boolean done = false;
}

class ReceiveOneMessage implements Runnable {

    MulticastSocket s;
    InetAddress group;
    FinishedSending finished;

    ReceiveOneMessage(MulticastSocket s, InetAddress group, FinishedSending finished) {
        this.s = s;
        this.group = group;
        this.finished = finished;
    }

    public void run() {
        byte[] buf = new byte[1000];
        DatagramPacket recv = new DatagramPacket(buf, buf.length);
        try {
            s.receive(recv);
            System.out.println(Arrays.toString(recv.getData()));
            finished.done = true;
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
